/**
 * @author haina.z@163.com
 * @brief header file.
 * @version V1.0
 */

#ifndef __CSP_INTERRUPT_H
#define __CSP_INTERRUPT_H

/** Includes -----------------------------------------------------------------*/
#include "public_defs.h"

/** Pre-compile check --------------------------------------------------------*/
#ifndef __CHIP
    #error "Please include me in the chip header file!"
#endif

/** C++ { --------------------------------------------------------------------*/
#ifdef __cplusplus
extern "C"
{
#endif

/** Macros (#define) ---------------------------------------------------------*/

/** Type definitions ---------------------------------------------------------*/
typedef uint32_t TMcuIntFlag;

/** External variable declarations (extern) ----------------------------------*/

/** Function declarations (prototypes) ---------------------------------------*/

/** Macros (#define) ---------------------------------------------------------*/

// Disable and enable interrupt
#define mCsp_DisableInterrupt()                 __disable_irq() // Except NMI and HardFault interrupt
#define mCsp_EnableInterrupt()                  __enable_irq()

/**
 * TMcuIntFlag kIntFlag;
 * kIntFlag = mCsp_GetMcuInt();
 * mCsp_DisableInterrupt();
 * ......
 * mCsp_SetMcuInt(kIntFlag);
 */
#define mCsp_GetMcuInt()                        __get_PRIMASK()
#define mCsp_SetMcuInt(flag)                    __set_PRIMASK(flag)

// Critical protection
#define mCsp_EnterCritical()                    do { kIntFlag = mCsp_GetMcuInt(); mCsp_DisableInterrupt(); } while(0)
#define mCsp_ExitCritical()                     mCsp_SetMcuInt(kIntFlag)

// Atomic operation
#define mAtomicOperation(code) \
do { \
    TMcuIntFlag primask_bit = __get_PRIMASK(); \
    __set_PRIMASK(1); /* same as __disable_irq(); */ \
    {code} \
    __set_PRIMASK(primask_bit); \
} while(0)

/** C++ } --------------------------------------------------------------------*/
#ifdef __cplusplus
}
#endif

#endif // CSP_INTERRUPT
/******************************** End of file *********************************/
